#include "file.h"

int ITemp_File_Init(char * address){
	system("/home/pi/modules/ITemp.sh allclear");
	return 0;
}

int ITemp_File_Get(char * address, struct IntTemp_T ** p){
	struct IntTemp_T * itemp_t = * p;
	FILE * fp;
	char * str = (char *)malloc(50);
	char * value = (char *)malloc(50);
	char * str_buf = (char *)malloc(50);
	char * value_buf = (char *)malloc(50);
	int i = 0;
	int ret = 0;
	if((fp = fopen(address, "r")) == NULL){
		ret = 1;
		goto end;
	}
	for(i = 1; i > 0; i++){
		if(i <= 2){
			memset(str_buf, 0 , 50);
			memset(value_buf, 0 , 50);
			fscanf(fp, "%s => %s ,", str_buf, value_buf);
		}else{
			memset(str_buf, 0 , 50);
			memset(value_buf, 0 , 50);
			fscanf(fp, "%s => %s ,", str_buf, value_buf);
			snprintf(str, strlen(str_buf)-1, "%s", str_buf+1);
			snprintf(value, strlen(value_buf)-1, "%s", value_buf+1);
			//DEBUG("%d:%s => [%d]", i, str, atoi(value));
			if(strcmp(str, "isDie") == 0){
				*(itemp_t->isDie) = atoi(value);
			}else if(strcmp(str, "auto_air") == 0){
				*(itemp_t->auto_air) =  atoi(value);
			}else if(strcmp(str, "OP") == 0){
				*(itemp_t->air_cont) =  atoi(value);
			}else if(strcmp(str, "AIR_STATUS") == 0){
				*(itemp_t->air_status) =  atoi(value);
			}else if(strcmp(str, "AIR_TEMP") == 0){
				*(itemp_t->air_temp) =  atoi(value);
			}else if(strcmp(str, "TEMP") == 0){
				*(itemp_t->temp) =  atoi(value);
			}else if(strcmp(str, "END") == 0){
				//DEBUG("this is the end of conf.php");
				break;
			}
		}
	}
	fclose(fp);
end:
	if(str != NULL)
		free(str);
	if(value != NULL)
		free(value);
	if(str_buf != NULL)
		free(str_buf);
	if(value_buf != NULL)
		free(value_buf);
	return ret;
}

int ITemp_File_Set(char * address, char * name, int value){
	char * value_c = (char *)malloc(200);
	snprintf(value_c, 200, "/home/pi/modules/ITemp.sh %s %d %s", name, value, address);
	DEBUG("system : %s", value_c);
	system(value_c);
	//system("/home/pi/modules/ITemp.sh %s %s %s",name,value_c,address);
	if(value_c != NULL)
		free(value_c);
	return 0;
}

int ITemp_File_Write(char * address, char * str){
	FILE * fp;
	int ret = 0;
	time_t timep;
	char * buf = (char *)malloc (2048);
	time(&timep);
	if((fp = fopen(address, "a")) == NULL){
		ret = 1;
		goto end;
	}
	memset(buf , 0 ,2048);
	snprintf(buf, 2048, "%s --> %s", ctime(&timep), str);
	fprintf(fp,"%s\n", buf);
	fclose(fp);
end:
	if(buf != NULL)
		free(buf);
	return ret;

}
